package com.xinwei.leetcode.链表;

import com.xinwei.linearExercise.List;

// https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
public class _1290_二进制链表转整数 {
    // 使用反转后常规方法转成十进制
    public int getDecimalValue(ListNode head) {
        if (head.val == 0) return 0;
        ListNode node = reverseList(head);
        int num = 0;
        while (node != null) {
            num += node.val * Math.pow(2, num);
            node = node.next;
            num++;
        }
        return num;
    }

    private ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    // 反推十进制转成二进制的方法
    public int getDecimalValue1(ListNode head) {
        int sum = 0;
        ListNode curNode = head;
        while (curNode != null) {
            sum = sum * 2 + curNode.val;
            curNode = curNode.next;
        }
        return sum;
    }

    
}
